package com.q.tqb.activity.grab;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Rect;
import android.graphics.drawable.AnimationDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.ZoomControls;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.CircleOptions;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.Stroke;
import com.baidu.mapapi.map.TextureMapView;
import com.baidu.mapapi.model.LatLng;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.reflect.TypeToken;

import com.q.tqb.R;
import com.q.tqb.activity.ViewPagerImageActivity;
import com.q.tqb.base.AppConst;
import com.q.tqb.base.BaseActivity;
import com.q.tqb.model.GetPacketInfo;
import com.q.tqb.model.RedDetailInfo;
import com.q.tqb.model.RedMapListInfo;

import com.q.tqb.util.DeviceUtil;
import com.q.tqb.util.LogUtil;
import com.q.tqb.util.MD5Util;
import com.q.tqb.util.SPUtil;
import com.q.tqb.util.StringUtil;
import com.q.tqb.util.http.IResponse;
import com.q.tqb.util.http.OkHttpUtil;
import com.q.tqb.view.CircleImageView;

import com.q.tqb.view.SoundButton;

import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

public class GrabMapActivity extends BaseActivity {

    @BindView(R.id.map_view)
    TextureMapView mMapView;

    @BindView(R.id.rl_head)
    RelativeLayout mRlHead;

    @BindView(R.id.iv_head)
    CircleImageView mIvHead;

    @BindView(R.id.iv_vip)
    ImageView mIvVip;
    @BindView(R.id.tv_name)
    TextView mTvName;


    @BindView(R.id.tv_money)
    TextView mTvMoney;
    @BindView(R.id.tv_amount)
    TextView mTvAmount;
    @BindView(R.id.tv_content)
    TextView mTvContent;
    @BindView(R.id.bt_play)
    SoundButton mBtPlay;
    @BindView(R.id.rl_detail)
    RelativeLayout mRlDetail;
    @BindView(R.id.iv_location)
    ImageView mIvLocation;
    @BindView(R.id.iv_content)
    ImageView mIvContent;
    @BindView(R.id.rl_open_red)
    RelativeLayout mRlOpenRed;
    @BindView(R.id.tv_get_money)
    TextView mTvGetMoney;
    @BindView(R.id.tv_play_money)
    TextView tvPlayMoney;
    @BindView(R.id.tv_navigation)
    TextView tvNavigation;
    @BindView(R.id.tv_call)
    TextView tvCall;
    @BindView(R.id.iv_open_money)
    ImageView mIvOpenMoney;
    @BindView(R.id.ll_red_result)
    LinearLayout mLlRedResult;
    @BindView(R.id.ll_store)
    LinearLayout mLlStore;
    @BindView(R.id.rl_red)
    RelativeLayout mRlRed;


    private BaiduMap mBaiduMap;


    public LocationClient mLocationClient = null;
    private MyLocationListener myListener = new MyLocationListener();


    private int ownUid;
    private int currentRid;

    private boolean isCanFinish;
    private boolean isOpen;

    private RedMapListInfo redMapListInfo;
    private RedDetailInfo redDetailInfo;

    private AnimationDrawable animationDrawable;

    private LatLng currentLag;


    @Override
    public int getLayoutId() {
        return R.layout.activity_grab_map;
    }

    @Override
    public void init(Bundle savedInstanceState) {

        ownUid = (int) SPUtil.get(this, "uid", 0);
        setTitle("地图红包");
        mBaiduMap = mMapView.getMap();
        mBaiduMap.setMyLocationEnabled(true);

        View child = mMapView.getChildAt(1);
        if (child != null && (child instanceof ImageView || child instanceof ZoomControls)) {
            child.setVisibility(View.INVISIBLE);
        }

        // 不显示地图上比例尺
        mMapView.showScaleControl(false);

        initLocation();


        mBtPlay.setAudioFinishRecorderListener(new SoundButton.AudioFinishRecorderListener() {
            @Override
            public void onFinished(String content) {
                if (redDetailInfo == null) {
                    showToast("请检查网络！");
                    return;
                }
                if (StringUtil.isMate(content, redDetailInfo.getGet_secret())) {
                    mRlDetail.setVisibility(View.GONE);
                    mRlRed.setVisibility(View.VISIBLE);
                    mRlOpenRed.setVisibility(View.VISIBLE);
                    ScaleAnimation animation = new ScaleAnimation(0.0f, 1.0f, 0.0f, 1.0f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
                    animation.setDuration(500);
                    mRlOpenRed.startAnimation(animation);
                } else {
                    showToast("识别错误" + content);
                }
            }
        });


        mBaiduMap.setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {
                currentRid = marker.getExtraInfo().getInt("rid");
                currentLag = marker.getPosition();
                getData();
                return true;
            }
        });
    }


    private void initLocation() {
        mLocationClient = new LocationClient(this);
        mLocationClient.registerLocationListener(myListener);
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        option.setCoorType("bd09ll");
        //可选，设置发起定位请求的间隔，int类型，单位ms
        option.setScanSpan(0);
        option.setOpenGps(true);
        option.setLocationNotify(false);
        //可选，定位SDK内部是一个service，并放到了独立进程。
        //设置是否在stop的时候杀死这个进程，默认（建议）不杀死，即setIgnoreKillProcess(true)
        option.setIgnoreKillProcess(false);
        option.setWifiCacheTimeOut(5 * 60 * 1000);
        mLocationClient.setLocOption(option);
        mLocationClient.start();

    }

    @OnClick({R.id.iv_back, R.id.rl_open_red, R.id.iv_content, R.id.iv_location, R.id.tv_navigation, R.id.tv_call})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_navigation:
                setUpGaodeAppByMine();
                break;
            case R.id.tv_call:
                callTel();
                break;
            case R.id.iv_location:
                mProgressDialog.show();
                initLocation();
                break;
            case R.id.rl_open_red:
                if (!isOpen) {
                    grabRed();
                }
                break;
            case R.id.iv_content:
                if (redDetailInfo != null) {
                    String[] images = new String[1];
                    images[0] = redDetailInfo.getPacket_picture();
                    Intent intent = new Intent(GrabMapActivity.this, ViewPagerImageActivity.class);
                    intent.putExtra("images", images);
                    intent.putExtra("position", 0);
                    startActivity(intent);
                }
                break;
            default:
                break;
        }
    }

    private void callTel() {
        final AlertDialog.Builder normalDialog = new AlertDialog.Builder(GrabMapActivity.this);
        normalDialog.setTitle("温馨提示");
        normalDialog.setMessage("是否拨打电话" + redDetailInfo.getMerchant_phone() + "?");
        normalDialog.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + redDetailInfo.getMerchant_phone()));
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(intent);
                    }
                });
        normalDialog.setNegativeButton("取消", null);
        // 显示
        normalDialog.show();
    }


    private class MyLocationListener extends BDAbstractLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            mProgressDialog.dismiss();
            mBaiduMap.clear();

            LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
            MapStatusUpdate u = MapStatusUpdateFactory.newLatLngZoom(latLng, 15f);
            mBaiduMap.animateMapStatus(u);
            getListData(latLng);

            BitmapDescriptor bitmap = BitmapDescriptorFactory.fromResource(R.drawable.ic_map_location);

            OverlayOptions option = new MarkerOptions()
                    .position(latLng)
                    .icon(bitmap);
            mBaiduMap.addOverlay(option);

            OverlayOptions ooCircle = new CircleOptions()
                    .center(latLng)
                    .stroke(new Stroke(1, 0xff069B14))
                    .zIndex(15)
                    .fillColor(0x22069B14)
                    .radius(2000);
            mBaiduMap.addOverlay(ooCircle);

        }
    }


    /**
     * 红包mark数据
     */
    private void getListData(LatLng latLng) {
        Map<String, String> map = new HashMap<>();
        map.put("longitude", latLng.longitude + "");
        map.put("latitude", latLng.latitude + "");
        map.put("long", "2000");
        //  LogUtil.i(map.toString());
        mProgressDialog.show();
        OkHttpUtil.getInstance().post(GrabMapActivity.this, AppConst.URL_GET_MAP_LIST, map, new IResponse() {
            @Override
            public void onSuccess(JsonElement element) {
                mProgressDialog.dismiss();
                // LogUtil.i(element.toString());
                Gson gson = new Gson();
                ArrayList<RedMapListInfo> redMapListInfos = gson.fromJson(element, new TypeToken<ArrayList<RedMapListInfo>>() {
                }.getType());
                int size = redMapListInfos.size();
                BitmapDescriptor bitmap = BitmapDescriptorFactory.fromResource(R.drawable.ic_location_red);
                for (int i = 0; i < size; i++) {
                    redMapListInfo = redMapListInfos.get(i);
                    LatLng curLatLng = new LatLng(Double.valueOf(redMapListInfo.getLatitude()), Double.valueOf(redMapListInfo.getLongitude()));

                    OverlayOptions option = new MarkerOptions()
                            .position(curLatLng)
                            .icon(bitmap);
                    Marker marker = (Marker) mBaiduMap.addOverlay(option);
                    Bundle mBundle = new Bundle();
                    mBundle.putInt("rid", redMapListInfo.getRid());
                    marker.setExtraInfo(mBundle);
                }
            }

            @Override
            public void onFailure(int statusCode, String errorMsg) {
                mProgressDialog.dismiss();
                LogUtil.i(errorMsg + "statusCode" + statusCode);
                showToast(errorMsg);
            }
        });
    }

    private void getData() {
        mProgressDialog.show();
        Map<String, String> map = new HashMap<>();
        map.put("rid", currentRid + "");
        map.put("uid", ownUid + "");

        OkHttpUtil.getInstance().post(GrabMapActivity.this, AppConst.URL_GET_PACKET_DETAIL, map, new IResponse() {
            @Override
            public void onSuccess(JsonElement element) {
                mProgressDialog.dismiss();
                isCanFinish = true;
                mRlDetail.setVisibility(View.VISIBLE);
                Gson gson = new Gson();
                String result = element.toString().replace("null", "\"\"");
                redDetailInfo = gson.fromJson(result, RedDetailInfo.class);


                Glide
                        .with(GrabMapActivity.this)
                        .load(redDetailInfo.getHeader())
                        .skipMemoryCache(true)
                        .into(new SimpleTarget<GlideDrawable>() {
                            @Override
                            public void onResourceReady(GlideDrawable resource, GlideAnimation<? super GlideDrawable> glideAnimation) {
                                mIvHead.setImageDrawable(resource);
                            }
                        });

                Glide
                        .with(GrabMapActivity.this)
                        .load(redDetailInfo.getPacket_picture())
                        .skipMemoryCache(true)
                        .into(mIvContent);


                mTvContent.setText(redDetailInfo.getGet_secret());
                mTvName.setText(redDetailInfo.getNickname());
                mTvMoney.setText("共" + redDetailInfo.getPacket_money() + "元");
                mTvAmount.setText(redDetailInfo.getGet_num() + "/" + redDetailInfo.getPacket_num() + "个");

                tvPlayMoney.setVisibility(View.GONE);
                mBtPlay.setVisibility(View.VISIBLE);

                if (redDetailInfo.getIs_get() == 1) {
                    tvPlayMoney.setText("已领取该红包:" + redDetailInfo.getGet_money() + "元");
                    tvPlayMoney.setVisibility(View.VISIBLE);
                    mBtPlay.setVisibility(View.GONE);
                } else if (redDetailInfo.getPacket_num() == redDetailInfo.getGet_num()) {
                    tvPlayMoney.setText("红包已领取完");
                    tvPlayMoney.setVisibility(View.VISIBLE);
                    mBtPlay.setVisibility(View.GONE);
                } else if (redDetailInfo.getCan_get() == 0) {
                    tvPlayMoney.setText("今日领取红包次数已用完！");
                    tvPlayMoney.setVisibility(View.VISIBLE);
                    mBtPlay.setVisibility(View.GONE);
                }

                if (redDetailInfo.getIs_users_agent() == 1) {
                    mIvVip.setVisibility(View.VISIBLE);
                } else {
                    mIvVip.setVisibility(View.INVISIBLE);
                }

                if (TextUtils.isEmpty(redDetailInfo.getMerchant_name())) {
                    mLlStore.setVisibility(View.GONE);
                } else {
                    mLlStore.setVisibility(View.VISIBLE);
                }

            }

            @Override
            public void onFailure(int statusCode, String errorMsg) {
                mProgressDialog.dismiss();
                LogUtil.i(errorMsg + "statusCode" + statusCode);
                showToast(errorMsg);
            }
        });
    }

    /**
     * 抢红包
     */
    private void grabRed() {

        isOpen = true;
        animationDrawable = (AnimationDrawable) mIvOpenMoney.getDrawable();
        animationDrawable.start();

        Map<String, String> map = new HashMap<>();
        map.put("rid", currentRid + "");
        map.put("uid", ownUid + "");
        map.put("token", StringUtil.getToken(ownUid));
        String addressCode = SPUtil.getString(GrabMapActivity.this, "addressCode");
        map.put("address", addressCode);
        //   LogUtil.i(map.toString());
        OkHttpUtil.getInstance().post(GrabMapActivity.this, AppConst.URL_GET_PACKET, map, new IResponse() {
            @Override
            public void onSuccess(JsonElement element) {
                Gson gson = new Gson();
                String result = element.toString().replace("null", "\"\"");
                GetPacketInfo getPacketInfo = gson.fromJson(result, GetPacketInfo.class);

                animationDrawable.stop();
                mIvOpenMoney.setImageResource(R.drawable.list_open);
                String getMoney = getPacketInfo.data;

                grabRedSuccess(getMoney);
            }

            @Override
            public void onFailure(int statusCode, String errorMsg) {
                animationDrawable.stop();
                mRlOpenRed.setVisibility(View.GONE);
                isOpen = false;
                LogUtil.i(errorMsg + "statusCode" + statusCode);
                showToast(errorMsg);
            }
        });
    }


    /**
     * 抢红包成功
     */
    private void grabRedSuccess(String money) {
        ScaleAnimation animation = new ScaleAnimation(1.0f, 0.0f, 1.0f, 0.0f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        animation.setDuration(600);
        animation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                mRlOpenRed.setVisibility(View.GONE);
                mLlRedResult.setVisibility(View.VISIBLE);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        mRlOpenRed.startAnimation(animation);
        mTvGetMoney.setText(money);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                mLlRedResult.setVisibility(View.GONE);
                mRlRed.setVisibility(View.GONE);
                isCanFinish = false;
                isOpen = false;
            }
        }, 1700);
    }


    @Override
    public void onBackPressed() {
        if (isCanFinish) {
            mRlRed.setVisibility(View.INVISIBLE);
            mRlDetail.setVisibility(View.INVISIBLE);
            isOpen = false;
            isCanFinish = false;
        } else {
            super.onBackPressed();
        }
    }


    /**
     * 导航
     */
    private void setUpGaodeAppByMine() {
        AlertDialog.Builder builder = new AlertDialog.Builder(GrabMapActivity.this);
        builder.setTitle("选择导航地图");
        //    指定下拉列表的显示数据
        final String[] cities = {"百度地图", "高德地图", "腾讯地图"};
        //    设置一个下拉的列表选择项
        builder.setItems(cities, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (which == 0) {
                    if (DeviceUtil.isAvilible(GrabMapActivity.this, "com.baidu.BaiduMap")) {
                        try {
                            Intent intent = Intent.getIntent("intent://map/direction?" +
                                    "destination=latlng:" + currentLag.latitude + "," + currentLag.longitude + "|name:红包位置" +    //终点
                                    "&mode=walk&" +     //导航路线方式
                                    "&src=appname#Intent;scheme=bdapp;package=com.baidu.BaiduMap;end");
                            startActivity(intent); //启动调用
                        } catch (URISyntaxException e) {
                            e.printStackTrace();
                        }
                    } else {
                        showToast("您未安装百度地图");
                    }
                } else if (which == 1) {
                    if (DeviceUtil.isAvilible(GrabMapActivity.this, "com.autonavi.minimap")) {
                        try {
                            Intent intent = Intent.getIntent("androidamap://route?sourceApplication=softname&sname=我的位置&dlat=" + currentLag.latitude + "&dlon=" + currentLag.longitude + "&dname=" + "红包位置" + "&dev=0&m=0&t=2");
                            startActivity(intent);
                        } catch (URISyntaxException e) {
                            e.printStackTrace();
                        }

                    } else {
                        showToast("您未安装高德地图");
                    }
                } else {
                    if (DeviceUtil.isAvilible(GrabMapActivity.this, "com.tencent.map")) {
                        StringBuffer stringBuffer = new StringBuffer("qqmap://map/")
                                .append("routeplan?")
                                .append("type=")
                                .append("walk")
                                .append("&to=")
                                .append("红包位置")
                                .append("&tocoord=")
                                .append(currentLag.latitude + "," + currentLag.longitude)
                                .append("&referer=")
                                .append("淘趣包");

                        Intent intent = new Intent();
                        intent.setData(Uri.parse(stringBuffer.toString()));
                        startActivity(intent);
                    } else {
                        showToast("您未安装腾讯地图");
                    }
                }

            }
        });
        builder.show();
    }


}
